from pymongo import Connection
from time import time
import random
import csv
import subprocess
from XW_Inverter import XW_Inverter
import InvertModes


PORT = '/dev/tty.usbserial-FTUTUPP2' #Enter the number needed here. 
ADDRESS = [0x89,0x65,0xc3]

Inverter = XW_Inverter(PORT,ADDRESS[0])

connection = Connection()
db = connection.string0001

## Building Load values! 

subprocess.call(['/Users/batterylab/seeya_node/ftpDraw'],shell=True)
blah = open('mb-250.log')
blah = blah.read()
blah = blah.split(',')
print blah

load = float(blah[6]) + float(blah[13])
load1 = float(blah[6])
load2 = float(blah[13])


#remove this from all UTC times to shift to Eastern Time - Timezone conversion. Valario addition, ask him for edits
timeZone=4*60*60

#Database collection formation

realtime = db.realtime
sensors = db.sensors
control = db.control.find_one({"label":0})
settings = db.settings
Nisensors = db.NIsensors.find_one({"label" : 0})

# data from the inverters


Asoc= 0.0
Aiac= 0.0
Avac= 0.0
Aidc= 0.0
tpiac = 0.0
tpoac = 0.0

writer = ({"label":0})

#function to retrieve data

for i in range(0,3):
	ii = str(i)
	
	Inverter.address = ADDRESS[i]
	
	iac = Inverter.getACOutCurr()
	piac = Inverter.getACInPowe1()
	poac = Inverter.getACOutPower()
	vac = Inverter.getACInVolt1()
	vdc = Inverter.getDCOutVolt()
	idc = Inverter.getDCOutCurr() 
	soc = Inverter.getBatSOC()
	charge = Inverter.getChargeState()
	invert = Inverter.getInvertState()
	temperture = Inverter.getBatTemp()
	tpoac = poac + tpoac
	tpiac = piac + tpiac
	Niv0 = Nisensors['Niv0']
	Niv1 = Nisensors['Niv1']
	Niv2 = Nisensors['Niv2']
	Niv3 = Nisensors['Niv3']
	
	## Writes the values to the database
	
	writer.update( { "vdc" + ii : 50*random.random() ,
		"idc" + ii : idc ,
		"iac" + ii : iac ,
		"piac" + ii : piac,
		"poac" + ii : poac, 
		"vac" + ii : vac ,
		"vdc" + ii : vdc ,
		"address" + ii : ADDRESS[i],
		"soc" + ii : soc,
		"charge" + ii : charge,
		"invert" + ii : invert,
		"temperature"+ ii : temperture,
		"time" : 1000*(time()-timeZone),
		"tpiac"  : tpiac,
		"tpoac"  : tpoac,
		"Aiac"   : Aiac,
		"Aidc"   : Aidc,
		"Niv0"	 : Niv0/1000.0,
		"Niv1"	 : Niv1/1000.0,
		"Niv2"	 : Niv2/1000.0,
		"Niv3"	 : Niv3/1000.0
	} )
	
	## average values

	Asoc=soc+ Asoc 
	Aiac=iac+ Aiac
	Avac=vac+ Avac
	Aidc=idc+ Aidc
	
	
sensors.update({'label':0},writer,True)


## Take database values!

invert_threshold = control["invert_threshold"]
charge_threshold = control["charge_threshold"]
status = control["status"]

chargeState = control["charge_state"]
sellState = control["sell_state"]

maxChargeRate = control["max_charge_current"]
maxSellRate = control["max_sell_current"]/3


meter = load
diff = 0
current = ((load-invert_threshold) * (1/40) )



# Write Realtime Data!!

writer=({"load" : load,
		 "load1" : load1,
		 "load2" : load2,
		 "power":diff,
		 "meter":meter,
		 "soc": soc,
		"time":1000*(time()-timeZone),
		"Niv0" : Niv0/1000.0,
		"Niv1" : Niv1/1000.0,
		"Niv2" : Niv2/1000.0,
		"Niv3" : Niv3/1000.0,
		
	} ) 
realtime.insert(writer)

# running methods


if(status == 1):
	## Status equal to 1 means that we are in Autopilot mode!
	## make into function "runAuto"
	writer=({'label':0})
	
	if (load > invert_threshold):
		
		#values that are changed when the load is greater than the allowed threshold!|
		charge = False
		sell = True
		diff = load - invert_threshold)
		meter = invert_threshold
		
		for i in range(0,3):
			ii=str(i)
			
			#Change Inverter Settings
			try:
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setChargeState(0)
				Inverter.setSellMode(1)
				Inverter.setMaxSellAmp()
			except:
				print "There was an error writing to the Inverters, continuing with the code though: AUTO SELL WRITE"
			
			#Write the settings to the database!

			writer.update( { "idc" + ii : current/3.0 ,
				"status" + ii : 1 , 
				"address" + ii : ADDRESS[i],
				"charge" + ii : 0,
				"sell" + ii : 1,
				"time" : 1000*(time()-timeZone),
				"sellrate" : maxSellRate*200,
				"chargerate" : maxChargeRate
				} )
	
else:
	## Status equal to 0 means that we are in Manual Mode!
	
	if (sellState == 1 && chargeState == 0):
		## If the sell state is set to True, do this!!!
		maxSell = (vdc * idc)/360
		
		for i in range(0,3):
			ii = str(i)
			
			##Change the Inverter Settings
			try:
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setChargeState(0)
				Inverter.setSellMode(1)
				Inverter.setMaxSellAmp(maxSell)
			except:
				"There was an error writing to the Inverters during MANUAL SELL WRITE"
				
	elif (sellState == 0 && chargeState == 1):
		
		for i in range(0,3):
			ii = str(i)
			
			##Change the Inverter Settings
			try:
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setSellState(0)
				Inverter.setChargeState(1)
				Inverter.setMaxSellAmp(maxSell)
				
			except:
				"There was an error writing to the Inverters during MANUAL CHARGE WRITE"
		


















